﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WorldOfMUDra
{
    public class PasswordStorageFile
    {
        string fname;
        string[] lines;
        Dictionary<string, string> UserPassDict = new Dictionary<string, string>();

        private void LoadDictionary()
        {
            try
            {
                foreach (string line in lines)
                {
                    string[] toks = line.Split(' ');
                    if (toks.Length >= 2)
                    {
                        Console.WriteLine("Adding username: " + toks[0] + " with password: " + toks[1]);
                        UserPassDict.Add(toks[0], toks[1]);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        public PasswordStorageFile(string filename)
        {
            fname = filename;
            try
            {
                lines = File.ReadAllLines(fname);
                LoadDictionary();
            }
            catch(Exception)
            {
                Console.WriteLine("Issues loading the file by name: "+filename);
            }
        }

        public static string CalculateMD5Hash(string input)
        {
            // step 1, calculate MD5 hash from input
            MD5 md5 = System.Security.Cryptography.MD5.Create();
            byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(input);
            byte[] hash = md5.ComputeHash(inputBytes);

            // step 2, convert byte array to hex string
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < hash.Length; i++)
            {
                sb.Append(hash[i].ToString("x2"));
            }
            return sb.ToString();
        }

        public string FileName
        {
            get { return fname; }
        }

        public void AddUser(string name, string pass)
        {
            if (!UserPassDict.ContainsKey(name))
            {
                string hashedPass = CalculateMD5Hash(pass);
                UserPassDict.Add(name, hashedPass);
                File.AppendAllText(fname, (Environment.NewLine + name + ' ' + hashedPass + Environment.NewLine));
                Console.WriteLine("Adding username: " + name + " with ENCRYPTED password: " + hashedPass);
            }
        }

        public bool VerifyPasswordOf(string name, string unhashedpass)
        {
            return (UserPassDict[name] == CalculateMD5Hash(unhashedpass));
        }

        public bool ContainsUser(string username)
        {
            return UserPassDict.ContainsKey(username);
        }
    }
}
